package org.example.type1;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 插入 Markdown 标记
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/1/6 17:13
 */
@SuppressWarnings("all")
public class MarkdownInsert {

    public static void main(String[] args) {
        String insertData = "";

        if (args == null || args.length == 0) {
            System.out.println("Error：Parameter cannot be empty！");
            return;
        }
        String type = args[0];
        if (type.equals("timeStamp")) {
            //插入时间戳
            Date nowDate = new Date();
            insertData = String.format("%1$tF %1$tT", nowDate);
        } else if (type.equals("title") && args.length == 2) {
            //插入标题
            String level = args[1];
            for (int i = 0; i < Integer.parseInt(level); i++) {
                insertData += "#";
            }
            insertData = insertData + "  " + insertData;
        } else if (type.equals("horizontalLine")) {
            insertData = "***";
        }

        //按下 alt + tab 健，将 cmd 窗口切换到下一层
        pressCtrlAndSingleKeyByNumber(KeyEvent.VK_ALT, KeyEvent.VK_TAB);

        try {
            //延迟 300 毫秒，等待上面切换窗口得动作
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //创建字符串选择器，并将内容传给它
        StringSelection stringSelection = new StringSelection(insertData);
        //创建系统剪贴板，并设置内容
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        //最后按 Ctrl + v 快捷键，将系统剪切板中得内容粘贴出来.
        pressCtrlAndSingleKeyByNumber(KeyEvent.VK_CONTROL, KeyEvent.VK_V);
    }

    /**
     * 模拟按下键盘快捷键，比如文档起始位置：Ctrl+Home，结束位置：Ctrl+End、复制 Ctrl + C、粘贴 Ctrl + V
     *
     * @param firstKeyCode ：第一个按键的值,如 Ctrl键是：KeyEvent.VK_CONTROL、alt 健是 KeyEvent.VK_ALT
     * @param keycode      ：第二个按键的值,如End键:KeyEvent.VK_END、Home键：KeyEvent.VK_HOME、V健：KeyEvent.VK_V
     */
    public static void pressCtrlAndSingleKeyByNumber(int firstKeyCode, int keycode) {
        try {
            Robot robot = new Robot();
            robot.keyPress(firstKeyCode);
            robot.keyPress(keycode);
            robot.keyRelease(keycode);
            robot.keyRelease(firstKeyCode);
            robot.delay(100);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}
